import React from 'react';
import { Input, InputNumber } from 'antd';
import PropTypes from 'prop-types';
import { isEqual } from 'lodash';

const InputGroup = Input.Group;
/**
 * 数字区间组件
 */
export default class NumRange extends React.Component {
  static propTypes = {
    precision: PropTypes.number, // 小数位
    onChange: PropTypes.func, // 值变化回调
  };

  static defaultProps = {
    precision: 0,
    onChange: () => { },
  };

  static getDerivedStateFromProps(nextProps) {
    const { value = [] } = nextProps;
    const [minNum, maxNum] = value;
    return {
      minNum,
      maxNum,
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (isEqual(nextState, this.state)) {
      return false;
    }
    return true;
  }

  state = {
    minNum: undefined,
    maxNum: undefined,
  };

  // min输入框输入事件
  onMinChange = value => {
    const { maxNum } = this.state;
    if (maxNum && value > maxNum) value = 0;
    this.setState({ minNum: value });
    this.props.onChange([value, maxNum]);
  };

  // max输入框输入事件
  onMaxChange = value => {
    const { minNum } = this.state;
    if (minNum && value < minNum) value = minNum;
    this.setState({ maxNum: value });
    this.props.onChange([minNum, value]);
  };

  render() {
    const { minNum, maxNum } = this.state;
    const { precision } = this.props;
    
    return (
      <InputGroup compact>
        <InputNumber
          max={10000000000}
          value={minNum}
          onChange={this.onMinChange}
          min={0}
          precision={precision}
          style={{ width: '42.5%' }}
        />
        <Input
          style={{ width: '15%', borderLeft: 0, pointerEvents: 'none', backgroundColor: '#fff' }}
          placeholder="~"
          disabled
        />
        <InputNumber
          max={10000000000}
          min={0}
          value={maxNum}
          onChange={this.onMaxChange}
          precision={precision}
          style={{ borderLeft: 0, width: '42.5%' }}
        />
      </InputGroup>
    );
  }
}
